<template>
  <div>
    <el-row style="padding: 20px">
      <el-col :span="24">
        <el-form :model="ruleForm" status-icon label-position="top"
                 :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="发表标题:" prop="title">
            <el-col :span="10">
              <el-input type="text" v-model="ruleForm.title" placeholder="请输入标题"
                        autocomplete="off"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item  >
            <el-col :span="24">
              <el-form-item label="发布内容:" >
                <mavon-editor
                    v-model="ruleForm.content"
                    ref="md"
                    @imgAdd="imgAdd"
                    :ishljs="true"
                    style="min-height: 400px"
                />

              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="2" :offset="22">
              <el-button @click="submitForm('ruleForm')" type="primary">提交</el-button>
            </el-col>
<!--            <el-col :span="4" :offset="1">-->
<!--              <el-button type="primary"></el-button>-->
<!--            </el-col>-->
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

  </div>
</template>

<script>
export default {
  name: "writePage",
  components:{},
  data(){
    var titleValidator = (rule,value,callback)=>{
      if (value === ''){
        callback(new Error("标题不能为空!"))
      }else{
        callback();
      }
    }
    return{
      ruleForm:{
        title:'',
        content:'',
        uid:''
      },
      rules:{
        title:[
          {validator:titleValidator,trigger:'blur'}
        ]
      }
    }
  },
  methods: {
    // 将图片上传到服务器，返回地址替换到md中
    imgAdd(pos, $file){
      //将图片上传到服务器
      let formdata = new FormData()
      formdata.append('file', $file)
      this.$api.upload(formdata).then(res => {
        //将返回的url替换到文本原位置
        this.$refs.md.$img2Url(pos, res.data);
      }).catch(err => {
        console.log(err)
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //获取当前用户的id
          this.ruleForm.uid = JSON.parse(localStorage.getItem('user')).id;
          this.$api.addArticle(this.ruleForm).then((res)=>{
            if (res.code === 200){
              this.$message.success("文章保存成功!");
            }else{
              this.$message.error("文章保存失败!");
            }
          })
        } else {
          this.$message.error("请输入标题!");
          return false;
        }
      });
    },
  }

}
</script>

<style lang="scss" scoped>

    /deep/ .el-form-item__label{
      margin-bottom: -15px;
    }
</style>